package com.maltys.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.maltys.entity.Goods;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author malty
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    RestHighLevelClient client;

    @RequestMapping("/es/creat_idx")
    public Object testMethod() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("malty_test_4");
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("index:" + response.index());
        System.out.println("acknowledged: " + response.isAcknowledged());
        return "ok";
    }

    @RequestMapping("/es/get_idx")
    public Object testGetIdxMethod() throws IOException {
        GetIndexRequest request = new GetIndexRequest("malty_test_4");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        System.out.println("aliases: " + response.getAliases());
        System.out.println("settings: " + response.getSettings());
        System.out.println("mappings: " + response.getMappings());
        return response.toString();
    }

    @RequestMapping("/es/del_idx")
    public Object testDelIdxMethod() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("malty_test_4");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println("acknowledged：：" + response.isAcknowledged());
        return response.toString();
    }

    /**
     * 配置映射
     *
     * @return json方式
     * @throws IOException
     */
    @RequestMapping("/es/mapping/put")
    public Object testPutDataMappingMethod() throws IOException {
        PutMappingRequest request = new PutMappingRequest("malty_test");
        request.source("{\"properties\":{\"title\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"subtitle\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"category\":{\"type\":\"keyword\"},\"brand\":{\"type\":\"keyword\"},\"price\":{\"type\":\"float\"},\"images\":{\"type\":\"keyword\",\"index\":false}}}", XContentType.JSON);
        AcknowledgedResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT);
        System.out.println("acknowledged：：" + response.isAcknowledged());
        return response.toString();
    }

    /**
     * 配置映射
     *
     * @return json方式
     * @throws IOException
     */
    @RequestMapping("/es/mapping/get")
    public Object testGetDataMappingMethod() throws IOException {
        GetMappingsRequest request = new GetMappingsRequest();
        request.indices("malty_test");
        GetMappingsResponse response = client.indices().getMapping(request, RequestOptions.DEFAULT);
        //3.打印响应结果
        System.out.println("mappings::" + response.mappings());
        System.out.println("Source::" + response.mappings().get("malty_test").getSourceAsMap());
        return response.toString();
    }

    @PostMapping("/es/doc/create")
    public Object testCreateDocMethod() throws IOException {
        IndexRequest request = new IndexRequest();
        request.index("malty_test");
        request.type("_doc");
        request.id("2");
        Goods goods = new Goods(2, "小米手机8", "小米", "手机", "小米", 6999.00, "http://image.baidu.com/13123.jpg");
        String goodJsonStr = new ObjectMapper().writeValueAsString(goods);
        request.source(goodJsonStr, XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println("_index：：" + response.getIndex());
        System.out.println("_type：：" + response.getType());
        System.out.println("_id：：" + response.getId());
        System.out.println("result：：" + response.getResult());
        return response.getResult();
    }

    @PostMapping("/es/doc/update")
    public Object testUpdateDocMethod() throws IOException {
        UpdateRequest request = new UpdateRequest();
        request.index("malty_test");
        request.type("_doc");
        request.id("1");
        Goods goods = new Goods(1, "小米手机", "小米", "手机", "小米", 6999.00, "http://image.baidu.com/13123.jpg");
        String goodJsonStr = new ObjectMapper().writeValueAsString(goods);
        request.doc(goodJsonStr, XContentType.JSON);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println("_index：：" + response.getIndex());
        System.out.println("_type：：" + response.getType());
        System.out.println("_id：：" + response.getId());
        System.out.println("result：：" + response.getResult());
        return response.getResult();
    }

    @PostMapping("/es/doc/query_by_id")
    public Object testQueryDocMethod() throws IOException {
        GetRequest request = new GetRequest();
        request.index("malty_test");
        request.type("_doc");
        request.id("1");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println("_index：：" + response.getIndex());
        System.out.println("_type：：" + response.getType());
        System.out.println("_id：：" + response.getId());
        System.out.println("result：：" + response.getSourceAsString());
        return response.getSource();
    }

    @PostMapping("/es/doc/del_by_id")
    public Object testDeleteDocMethod() throws IOException {
        DeleteRequest request = new DeleteRequest();
        request.index("malty_test");
        request.type("_doc");
        request.id("2");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println("_index：：" + response.getIndex());
        System.out.println("_type：：" + response.getType());
        System.out.println("_id：：" + response.getId());
        System.out.println("result：：" + response.getResult());
        return response.getResult();
    }

    @PostMapping("/es/doc/add_bulk")
    public void initData() throws IOException {
        //批量新增操作
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().type("_doc").index("malty_test").source(XContentType.JSON, "title", "大米手机", "images", "http://image.hero.com/12479122.jpg", "price", 3288, "category", "手机", "brand", "小米"));
        request.add(new IndexRequest().type("_doc").index("malty_test").source(XContentType.JSON, "title", "小米手机", "images", "http://image.hero.com/12479122.jpg", "price", 2699, "category", "手机", "brand", "小米"));
        request.add(new IndexRequest().type("_doc").index("malty_test").source(XContentType.JSON, "title", "小米电视4A", "images", "http://image.hero.com/12479122.jpg", "price", 4288, "category", "手机", "brand", "小米"));
        request.add(new IndexRequest().type("_doc").index("malty_test").source(XContentType.JSON, "title", "华为手机", "images", "http://image.hero.com/12479122.jpg", "price", 5288, "subtitle", "小米", "category", "手机", "brand", "小米"));
        request.add(new IndexRequest().type("_doc").index("malty_test").source(XContentType.JSON, "title", "apple手机", "images", "http://image.hero.com/12479122.jpg", "price", 5899.00, "category", "手机", "brand", "小米"));
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println("took::" + response.getTook());
        System.out.println("Items::" + response.getItems());
    }

    /**
     * 初始化查询数据
     */
    @GetMapping("/es/doc/query_bulk")
    public void queryBulk() throws IOException {
        //1.创建请求对象：查询所有
        SearchRequest request = new SearchRequest();
        request.types("_doc");
        request.indices("malty_test");
        //2.创建查询请求体构建器
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //设置查询方式：matchAll
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        //设置请求体
        request.source(sourceBuilder);
        //3.客户端发送请求，获取响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.打印响应结果
        SearchHits hits = response.getHits();
        System.out.println("took::" + response.getTook());
        System.out.println("time_out::" + response.isTimedOut());
        System.out.println("total::" + hits.getTotalHits());
        System.out.println("max_score::" + hits.getMaxScore());
        System.out.println("hits::::>>");
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
        }
        System.out.println("<<::::");
    }
}
